package com.nc.delivery_project.client.department_details;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.IntensityMap;
import com.google.gwt.visualization.client.visualizations.corechart.AreaChart;
import com.google.gwt.visualization.client.visualizations.corechart.AxisOptions;
import com.google.gwt.visualization.client.visualizations.corechart.BarChart;
import com.google.gwt.visualization.client.visualizations.corechart.Options;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.nc.delivery_project.client.ClientFactory;


import com.nc.delivery_project.client.request.DepartmentRequest;
import com.nc.delivery_project.shared.proxy.CityProxy;
import com.nc.delivery_project.shared.proxy.CountryProxy;
import com.nc.delivery_project.shared.proxy.DepartmentProxy;
import com.nc.delivery_project.shared.proxy.OrderWaypointProxy;
import com.nc.delivery_project.shared.proxy.StateProvinceProxy;

import java.util.ArrayList;
import java.util.List;


public class DepartmentDetailsActivity extends AbstractActivity implements DepartmentDetailsPresenter {
    
    private DepartmentDetailsView view;
    private ClientFactory clientFactory;
    
    private DepartmentProxy dept;
    
    private List<CityProxy> cities;
    
    private List<StateProvinceProxy> states;
    
    private List<CountryProxy> countries;
    
    private int deptId;
    
    private DepartmentRequest updateRequest;
    
    private int fetchedCount;
    
    private List<OrderWaypointProxy> ordersW;
    
    public DepartmentDetailsActivity(DepartmentDetailsPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        parseToken(place.getToken());
        updateRequest = clientFactory.getRequestFactory().createDepartmentRequest();
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
               
        fetchDepartment(deptId);
        fetchCities();
        fetchStateProvinces();
        fetchCountries();
   //     fetchOrderWaypoints(deptId);
        
        if (view == null) {
            view = new DepartmentDetailsView();
        }
        
        view.setPresenter(this);
        panel.setWidget(view);
        view.start();
        
        view.departmentIdLbl.setText(String.valueOf(deptId));

        initButtonHandlers();
    }

    

	@Override
    public void loadDepartmentDetails(DepartmentProxy dept) {
        view.departmentIdLbl.setText(String.valueOf(dept.getDeptId()));
        view.addressTxtBox.setText(dept.getAddress());
        view.postalCodeTxtBox.setText(dept.getPostalCode());
    }

    @Override
    public void update(DepartmentProxy dept) {
        updateRequest.update(dept).fire();
        Window.Location.reload();
    }

    @Override
    public void delete(int deptId) {
        clientFactory.getRequestFactory().createDepartmentRequest().delete(deptId).fire();
    }

    @Override
    public void fillCityDropBox(List<CityProxy> cities) {
        for (int i = 0; i < cities.size(); i++) {
        	CityProxy city = cities.get(i);
            view.cityLstBox.addItem(String.valueOf(city.getCityTitle()), String.valueOf(city.getCityId()));
            if (city.getCityId() == dept.getCity().getCityId()){
                view.cityLstBox.setItemSelected(i, true);
         
            }
        }
    }
    
    @Override
	public void fillStateProvinceDropBox(List<StateProvinceProxy> states) {
    	
     		for (int i = 0; i < states.size(); i++) {
				StateProvinceProxy state = states.get(i);	
				view.stateLstBox.addItem(state.getStateTitle(),String.valueOf(state.getStateId()));
				if (state.getStateId()==dept.getCity().getStatePr().getStateId())//405) //  у меня Одесса
					view.stateLstBox.setItemSelected(i, true);
			}
	}
    
    @Override
	public void fillCountryDropBox(List<CountryProxy> countries) {
    	for (int i = 0; i < countries.size(); i++) {
    		CountryProxy country = countries.get(i);	
			view.countryLstBox.addItem(country.getCountryTitle(),String.valueOf(country.getCountryId()));
			if (country.getCountryId()==dept.getCity().getStatePr().getCountry().getCountryId())
				view.countryLstBox.setItemSelected(i, true);
		}
	}

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }
    
    private void initButtonHandlers() {
        view.saveBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                dept.setAddress(view.addressTxtBox.getText());
                dept.setPostalCode(view.postalCodeTxtBox.getText());
                dept.setCity(cities.get(view.cityLstBox.getSelectedIndex()));
               
                update(dept);
            }
        });

        view.removeBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                delete(dept.getDeptId());
            }
        });


    }
    
    private void fetchDepartment(int id) {
    	DepartmentRequest departmentRequest = clientFactory.getRequestFactory().createDepartmentRequest();
        departmentRequest.read(id).with("city","city.statePr","city.statePr.country").fire(new Receiver<DepartmentProxy>() {
            @Override
            public void onSuccess(DepartmentProxy response) {
                GWT.log("departmentr fetched");
                dept = updateRequest.edit(response);
                
                if (++fetchedCount == 4) fillView();
                //if (++fetchedCount == 5) fillView();
            }
        });
    }
    
    private void fetchCities() {
        clientFactory.getRequestFactory().createCityRequest().read().fire(new Receiver<List<CityProxy>>() {
            @Override
            public void onSuccess(List<CityProxy> response) {
                GWT.log("cities fetched");
                cities = response;

                if (++fetchedCount == 4) fillView();
              //if (++fetchedCount == 5) fillView();
            }
        });
    }
    
    private void fetchStateProvinces() {
    	clientFactory.getRequestFactory().createStateProvinceRequest().read().fire(new Receiver<List<StateProvinceProxy>>() {
            @Override
            public void onSuccess(List<StateProvinceProxy> response) {
                GWT.log("statesprovinces fetched");
                states = response;

                if (++fetchedCount == 4) fillView();
              //if (++fetchedCount == 5) fillView();
            }
        });
        
	}
    
    private void fetchCountries() {
    	clientFactory.getRequestFactory().createCountryRequest().read().fire(new Receiver<List<CountryProxy>>() {
            @Override
            public void onSuccess(List<CountryProxy> response) {
                GWT.log("countries fetched");
                countries = response;

                if (++fetchedCount == 4) fillView();
              //if (++fetchedCount == 5) fillView();
            }
        });
	}
    

 /*   
	private void fetchOrderWaypoints(int deptId) {
		clientFactory.getRequestFactory().createOrderWaypointRequest().readByDepartmentId(deptId).with("department").fire(new Receiver<List<OrderWaypointProxy>>(){
		 @Override
            public void onSuccess(List<OrderWaypointProxy> response) {
            	GWT.log("orderWaypoints fetched");
            	ordersW=response;
            	if (++fetchedCount == 5) fillView();
            }

            @Override
            public void onFailure(ServerFailure error) {
                super.onFailure(error);
                GWT.log(error.toString());
            }
        });
	
	}
	*/
    
    private void fillView() {
        loadDepartmentDetails(dept);
        fillCityDropBox(cities);
        fillStateProvinceDropBox(states); 
        fillCountryDropBox(countries); 
        createVisualization();
    }

	private void createVisualization() {
		final TabPanel tabPanel = new TabPanel();
		
		view.panel.add(tabPanel);
         
		VisualizationUtils.loadVisualizationApi( new Runnable() {
			public void run() { 
				tabPanel.add(createAreaChart(dept), "Statistics(AreaChart) by "+dept.getAddress());
			}
		},  AreaChart.PACKAGE);
	}
	//----------- временные данные ----------
	String []date = {"14.01.2015", 
			"15.01.2015",
			"16.01.2015",
			"17.01.2015",
			"18.01.2015",
			"19.01.2015"};
	int acceptedOrders;
	int grantedOrders;
	List<String>  dates;
	{
	dates = new ArrayList<String>();
	    for (int i = 0; i < date.length; i++) {
	    	dates.add(date[i]);
		};
    }
	//--------------------------------------------------
	private Widget createAreaChart(DepartmentProxy dept) {
		
				 /* create Area chart */
			    Options options = Options.create();
			    options.setHeight(300);
			    options.setTitle("Performance by department № "+dept.getDeptId());
			    options.setWidth(600);
			    AxisOptions vAxisOptions = AxisOptions.create();
			    vAxisOptions.setMinValue(0);
			    vAxisOptions.setMaxValue(20);
			    options.setVAxisOptions(vAxisOptions);
			 /* create a datatable */
			    DataTable data = DataTable.create();
			    data.addColumn(ColumnType.STRING, "Date");
			    data.addColumn(ColumnType.NUMBER, "Accepted orders");
			    data.addColumn(ColumnType.NUMBER, "Granted orders");
			    data.addColumn(ColumnType.NUMBER, "Total orders");

			    data.addRows(dates.size());
			    
			    for (int i = 0; i < dates.size(); i++) {
			    	acceptedOrders = dept.getDeptId()+(i*(-1)^i)-250;
			    	grantedOrders = dept.getDeptId()+(i*(-2)^(2*i))-270;
			    	data.setValue(i, 0, dates.get(i));
			    	data.setValue(i, 1, acceptedOrders);
			    	data.setValue(i, 2, grantedOrders);
			    	data.setValue(i, 3, acceptedOrders+grantedOrders);
			    }
			
				return new AreaChart(data, options);
	}

   

	private void parseToken(String token) {
        try {
            deptId = Integer.parseInt(token);
        } catch (NumberFormatException e) {
            Window.alert("Unknown Token");
        }
    }

	
}
